package pl.register.android.activities.program;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.actionbarsherlock.app.SherlockFragment;
import pl.register.android.R;
import pl.register.android.activities.program.builder.HolidayProgramEditorDialogBuilder;
import pl.register.android.activities.program.builder.ProgramEditorDialogBuilder;
import pl.register.android.activities.program.logic.AsyncProgramsLoader;
import pl.register.android.activities.program.ui.HolidayLessonProgramListAdapter;
import pl.register.android.course.dialog.CreatorNextCourseDialogBuilder;
import pl.register.android.course.dialog.NotFoundPreviousCourseDialogBuilder;
import pl.register.android.course.factory.CreatorCourseMonitoring;
import pl.register.android.database.exception.NotFoundCourseException;
import pl.register.android.activities.program.logic.ProgramPresenter;
import pl.register.android.activities.program.ui.LessonProgramListAdapter;
import pl.register.android.activities.program.ui.ProgramView;
import pl.register.android.course.Course;
import pl.register.android.database.DatabaseAdapter;
import pl.register.android.lesson.LessonProgram;
import pl.register.android.preferences.ResotorePreferences;
import pl.register.android.program.Program;
import pl.register.android.year.Year;
import pl.register.android.year.YearType;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-12
 */
public class ProgramFragment extends SherlockFragment
        implements ProgramView, CompoundButton.OnCheckedChangeListener, View.OnClickListener, CreatorCourseMonitoring {

    private ImageButton imageBtnPrevious;

    private ImageButton imageBtnNext;

    private TextView tvTitle;

    private TextView tvStartYear;

    private TextView tvEndYear;

    private RadioButton rbFirstYear;

    private RadioButton rbSecondYear;

    private RadioButton rbThirdYear;

    private RadioButton rbIntensiveYear;

    private RadioButton rbHoliday1Year;

    private RadioButton rbHoliday2Year;

    private View vHolidayProgramLayout;

    private View vProgramLayout;

    private ListView lvLessonsProgram;

    private ListView lvHolidayLessonsProgram;

    private Map<YearType, RadioButton> rbYearsMap;


    private DatabaseAdapter databaseAdapter;

    private ProgramPresenter presenter;

    private LessonProgramListAdapter listAdapter;

    private HolidayLessonProgramListAdapter holidayListAdapter;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        databaseAdapter = new DatabaseAdapter(getActivity());
        databaseAdapter.open();
        presenter = new ProgramPresenter(databaseAdapter, this);
        View contentLayout = inflater.inflate(R.layout.program_layout, container, false);
        registerViews(contentLayout);
        setupContent(inflater);

        Course course = ResotorePreferences.getCourse(getActivity());
        new AsyncProgramsLoader(getActivity(), this, presenter, course).execute();
        return contentLayout;
    }

    private void registerViews(View content) {
        vProgramLayout = content.findViewById(R.id.table_layout);
        vHolidayProgramLayout = content.findViewById(R.id.holiday_table_layout);
        imageBtnPrevious = (ImageButton) content.findViewById(R.id.previous_button);
        imageBtnNext = (ImageButton) content.findViewById(R.id.next_button);
        tvTitle = (TextView) content.findViewById(R.id.title_table_text_view);
        tvStartYear = (TextView) content.findViewById(R.id.start_year_date_text_view);
        tvEndYear = (TextView) content.findViewById(R.id.end_year_date_text_view);
        rbFirstYear = (RadioButton) content.findViewById(R.id.first_year_radio_button);
        rbSecondYear = (RadioButton) content.findViewById(R.id.second_year_radio_button);
        rbThirdYear = (RadioButton) content.findViewById(R.id.third_year_radio_button);
        rbIntensiveYear = (RadioButton) content.findViewById(R.id.intensive_year_radio_button);
        rbHoliday1Year = (RadioButton) content.findViewById(R.id.holiday_I_year_radio_button);
        rbHoliday2Year = (RadioButton) content.findViewById(R.id.holiday_II_year_radio_button);
        lvLessonsProgram = (ListView) content.findViewById(R.id.lessons_program_list_view);
        lvHolidayLessonsProgram = (ListView) content.findViewById(R.id.lessons_holiday_program_list_view);
    }

    private void setupContent(LayoutInflater inflater) {
        listAdapter = new LessonProgramListAdapter(getActivity(), presenter, this);
        lvLessonsProgram.setAdapter(listAdapter);

        holidayListAdapter = new HolidayLessonProgramListAdapter(getActivity(), presenter, this);
        lvHolidayLessonsProgram.setAdapter(holidayListAdapter);

        imageBtnPrevious.setOnClickListener(this);
        imageBtnNext.setOnClickListener(this);

        rbYearsMap = new HashMap<YearType, RadioButton>();
        registerRadioButton(rbFirstYear, YearType.FIRST_YEAR);
        registerRadioButton(rbSecondYear, YearType.SECOND_YEAR);
        registerRadioButton(rbThirdYear, YearType.THIRD_YEAR);
        registerRadioButton(rbIntensiveYear, YearType.INTENSIVE_YEAR);
        registerRadioButton(rbHoliday1Year, YearType.HOLIDAY_I_YEAR);
        rbHoliday1Year.setText("W");
        rbHoliday2Year.setVisibility(View.GONE);
    }

    private void registerRadioButton(RadioButton radioButton, YearType yearType) {
        rbYearsMap.put(yearType, radioButton);
        radioButton.setText(yearType.getShortName());
        radioButton.setTag(yearType);
        radioButton.setOnCheckedChangeListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.next_button:
                try {
                    presenter.rebuildForNextCourse(getActivity());
                } catch (NotFoundCourseException e) {
                    showCreateCourseDialog();
                }
                break;
            case R.id.previous_button:
                try {
                    presenter.rebuildForPreviousCourse(getActivity());
                } catch (NotFoundCourseException e) {
                    showNotFoundCourseDialog();
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isSelected) {
        if (!isSelected) {
            return;
        }
        switch (buttonView.getId()) {
            case R.id.first_year_radio_button:
            case R.id.second_year_radio_button:
            case R.id.third_year_radio_button:
            case R.id.intensive_year_radio_button:
            case R.id.holiday_I_year_radio_button:
            case R.id.holiday_II_year_radio_button:
                YearType yearType = (YearType) buttonView.getTag();
                presenter.changeYearType(getActivity(), yearType);
                break;
        }
    }

    @Override
    public void populateCourse(String startYear, String endYear) {
        tvStartYear.setText(startYear);
        tvEndYear.setText(endYear);
    }

    @Override
    public void populateProgram(Year year, Program program) {
        if (year.getType().equals(YearType.HOLIDAY_I_YEAR) || year.getType().equals(YearType.HOLIDAY_II_YEAR)) {
            vProgramLayout.setVisibility(View.GONE);
            vHolidayProgramLayout.setVisibility(View.VISIBLE);
            holidayListAdapter.refreshItems(program.getLessons());
        } else {
            vProgramLayout.setVisibility(View.VISIBLE);
            vHolidayProgramLayout.setVisibility(View.GONE);
            listAdapter.refreshItems(program.getLessons());
        }
    }

    @Override
    public void refresh(Year year) {
        if (year.getType().equals(YearType.HOLIDAY_I_YEAR) || year.getType().equals(YearType.HOLIDAY_II_YEAR)) {
            holidayListAdapter.refresh();
        } else {
            listAdapter.refresh();
        }
    }

    @Override
    public void refreshTitle(Year year) {
        YearType yearType = year.getType();
        RadioButton radioButton = rbYearsMap.get(yearType);
        radioButton.setChecked(true);
        tvTitle.setText(yearType.getName());
    }

    @Override
    public void insertedNewCourse(Course course) {
        //
    }

    public void showEditProgramDialog(LessonProgram lessonProgram) {
        AlertDialog alertDialog = new ProgramEditorDialogBuilder(getActivity(), lessonProgram, presenter).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(750, 400);
    }

    public void showEditHolidayProgramDialog(LessonProgram lessonProgram) {
        AlertDialog alertDialog = new HolidayProgramEditorDialogBuilder(getActivity(), lessonProgram, presenter).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(750, 400);
    }

    private void showCreateCourseDialog() {
        AlertDialog alertDialog = new CreatorNextCourseDialogBuilder(getActivity(), this).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(600, 400);
    }

    private void showNotFoundCourseDialog() {
        AlertDialog alertDialog = new NotFoundPreviousCourseDialogBuilder(getActivity()).create();
        alertDialog.show();
        alertDialog.getWindow().setLayout(600, 400);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (databaseAdapter != null) {
            databaseAdapter.close();
        }
    }

}